package com.igeek.ch02.servlet;

import com.igeek.ch02.entity.User;
import com.igeek.ch02.service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "UserServlet", value = "/user")
public class UserServlet extends HttpServlet {

    private UserService userService = new UserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置中文友好
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        //获取会话
        HttpSession session = request.getSession();

        //获取请求参数
        String method = request.getParameter("method");
        if(method!=null && !method.equals("")){
            switch (method){
                case "login":
                    System.out.println("用户登录");
                    String username = request.getParameter("username");
                    String address = request.getParameter("address");
                    User user = userService.login(username, address);
                    if(user!=null){
                        //将登录成功的信息，传递到页面，设置请求属性
                        request.setAttribute("user" , user);
                        //将登录成功的信息，传递到页面，设置会话属性
                        session.setAttribute("sessionUser" , user);

                        //请求转发
                        request.getRequestDispatcher("success.jsp").forward(request,response);
                        //思考问题？ 响应重定向，请求域 和  会话域 哪一个数据会被传递下去？？？
                    }else{
                        response.sendRedirect("error.jsp");
                    }
                    break;
                case "register":
                    System.out.println("用户注册");

                    break;
                case "logout":
                    System.out.println("用户登出");
                    //销毁会话信息
                    session.invalidate();
                    response.sendRedirect("login.jsp");
                    break;
            }
        }
    }
}
